import logging
import os
from celery import Celery
from celery.utils.log import get_task_logger

from application import settings
from application.settings import BASE_DIR, CELERY_BEAT_SCHEDULE

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')

app = Celery('app_group', broker='redis://exam-redis:6379/0', backend='redis://exam-redis:6379/1')

# 获取 Celery 自带的日志记录器
logger = get_task_logger('my_celery_logger')

redis_password = os.getenv('REDIS_PASSWORD', '000000')

app.config_from_object({
    'broker_url': f'redis://:{redis_password}@exam-redis:6379/0',
    'result_backend': f'redis://:{redis_password}@exam-redis:6379/1',
    'timezone': 'Asia/Shanghai',
})

# 加载 Celery beat 配置，加载 CELERY_BEAT_SCHEDULE
app.conf.update(
    CELERY_BEAT_SCHEDULE=CELERY_BEAT_SCHEDULE,
)

# 自动发现所有注册了任务的 Django app
app.autodiscover_tasks(settings.INSTALLED_APPS)

# 设置日志文件路径
log_file = os.path.join(BASE_DIR, 'apps/utils/logs/celery.log')

# 确保日志文件已经创建
if not os.path.exists(os.path.dirname(log_file)):
    os.makedirs(os.path.dirname(log_file))

# 创建日志记录器的文件处理器
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
file_handler.setLevel(logging.INFO)

# 创建日志记录器的控制台处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
console_handler.setLevel(logging.INFO)

# 将文件和控制台处理器添加到 logger
logger.addHandler(file_handler)
logger.addHandler(console_handler)

logger.setLevel(logging.INFO)  # 设置日志级别为 INFO
